A brief analysis of the difference between int*p[] and int of *p[]

  • 2020-04-02 01:08:09
  • OfStack

Examples:
1) int* p[2] is an array of Pointers to int.
It can be used like this:

<SPAN style="BACKGROUND-COLOR: rgb(255,255,255)">#include <iostream>
using namespace std;
int main(int argc, char* argv[])
 {
int* p[2];
int a[3] = {1, 2, 3};
int b[4] = {4, 5, 6, 7};
p[0] = a;
p[1] = b;
for(int i = 0; i < 3; i++)
cout << *p[0] + i;// cout << **p + i;
cout << endl;
for(i = 0; i < 4; i++)
cout << *p[1] + i;// cout << **p + i;
return 0;
}</SPAN>

2) for int (*p)[2], it is equivalent to a two-dimensional array, except that it is an array of n rows and 2 columns.

<SPAN style="BACKGROUND-COLOR: rgb(255,255,255)">#include <iostream>
using namespace std;
void main() {
int (*p)[2];
int b[3][2] = {{1, 2}, {3, 4}, {5, 6}};
p = b;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 2; j++) //cout << p[i][j]; //cout << *(*(p+i)+j);
cout << endl;
}
}</SPAN>

Note:
(1) the number of rows is determined and the number of columns is not determined, that is, it is of type 2*n.
(2) is the pointer usage of n*2 type array, that is, the number of rows is not determined, the number of columns is determined.
The equivalent form of (1) is as follows:

<SPAN style="BACKGROUND-COLOR: rgb(255,255,255)">#include <iostream>
using namespace std;
void main() {
int** array;
array = new int* [2];
int a[3] = {1, 2, 3};
int b[4] = {4, 5, 6, 7};
array[0] = a; // *array = a;
array[1] = b; // *(array+1) = b;
for(int i = 0; i < 3; i++) cout << array[0][i];// cout << *array[0] + i;
cout << endl;
for(int j = 0; j < 4; j++) cout << array[1][j];// cout << *array[1] + j;
}</SPAN>

In fact, the above usage is this we often use dynamic two-dimensional array.

Related articles: